import { Module, DynamicModule, Global, MiddlewareConsumer, RequestMethod } from '@nestjs/common';
import { WinstonModule } from 'nest-winston';
import { LoggerService } from './logger.service';
import { LoggerMiddleware } from './logger.middleware';
import { createWinstonOptions, LoggerOptions, defaultLoggerOptions } from './logger.config';
import * as fs from 'fs';
import * as path from 'path';

@Global()
@Module({})
export class LoggerModule {
  /**
   * 注册日志模块
   * @param options 日志配置选项
   * @returns 动态模块
   */
  static forRoot(options: LoggerOptions = defaultLoggerOptions): DynamicModule {
    // 确保日志目录存在
    this.ensureLogDirectory(options.logDir);

    return {
      module: LoggerModule,
      imports: [WinstonModule.forRoot(createWinstonOptions(options))],
      providers: [LoggerService],
      exports: [LoggerService],
    };
  }

  /**
   * 注册日志模块（异步方式）
   * @param optionsFactory 异步配置工厂函数
   * @returns 动态模块
   */
  static forRootAsync(optionsFactory: () => Promise<LoggerOptions> | LoggerOptions): DynamicModule {
    return {
      module: LoggerModule,
      imports: [
        WinstonModule.forRootAsync({
          useFactory: async () => {
            const options = await optionsFactory();
            this.ensureLogDirectory(options.logDir);
            return createWinstonOptions(options);
          },
        }),
      ],
      providers: [LoggerService],
      exports: [LoggerService],
    };
  }

  /**
   * 配置中间件
   * @param consumer 中间件消费者
   */
  configure(consumer: MiddlewareConsumer) {
    consumer.apply(LoggerMiddleware).forRoutes({ path: '*', method: RequestMethod.ALL });
  }

  /**
   * 确保日志目录存在
   * @param logDir 日志目录路径
   */
  private static ensureLogDirectory(logDir: string): void {
    if (!fs.existsSync(logDir)) {
      fs.mkdirSync(logDir, { recursive: true });
    }
  }
}
